package com.ning.cloud.user.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ning.cloud.common.constant.CommonConstant;
import com.ning.cloud.common.exception.ServiceException;
import com.ning.cloud.framework.security.util.JwtTokenUtil;
import com.ning.cloud.user.dto.UserLoginDTO;
import com.ning.cloud.user.dto.UserRegisterDTO;
import com.ning.cloud.user.entity.AdminUserEntity;
import com.ning.cloud.user.mapper.AdminUserMapper;
import com.ning.cloud.user.request.UserLoginRequest;
import com.ning.cloud.user.request.UserRegisterRequest;
import com.ning.cloud.user.service.AdminUserService;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.ning.cloud.user.common.util.NumberUtil;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 后台用户 服务实现类
 * </p>
 *
 * @author kxn
 * @since 2025-08-07
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUserEntity> implements AdminUserService {

    private final static Integer LOGIN_EXPIRE_DAYS = 10; //登录过期天数

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    JwtTokenUtil jwtTokenUtil;

    /**
     * 生成登录token
     *
     * @return
     */
    private static String generateAccessToken() {
        return IdUtil.fastSimpleUUID();
    }

    public boolean isPasswordMatch(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    @Override
    public AdminUserEntity getUserByUsername(String username) {
        LambdaQueryWrapper<AdminUserEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminUserEntity::getUsername, username);
        return this.getBaseMapper().selectOne(lambdaQueryWrapper);
    }

    /**
     * 注册用户
     * @param userRegisterRequest
     * @return
     */
    @Override
    public UserRegisterDTO register(UserRegisterRequest userRegisterRequest) {
        AdminUserEntity adminUserEntity = this.getUserByUsername(userRegisterRequest.getUsername());
        if (adminUserEntity != null) {
            throw new ServiceException("账号已存在，重新注册");
        }
        String encodePassword = passwordEncoder.encode(userRegisterRequest.getPassword());

        adminUserEntity = new AdminUserEntity();
        adminUserEntity.setUsername(userRegisterRequest.getUsername());
        adminUserEntity.setPassword(encodePassword);
        adminUserEntity.setNickname(userRegisterRequest.getNickname());
        adminUserEntity.setStatus(CommonConstant.STATUS_ENABLED);
        this.save(adminUserEntity);

        UserRegisterDTO userRegisterDTO = new UserRegisterDTO();
        userRegisterDTO.setUserId(adminUserEntity.getId());
        userRegisterDTO.setUsername(adminUserEntity.getUsername());
        return userRegisterDTO;
    }


    /**
     * 登录
     * @param userLoginRequest
     * @return
     */
    @Override
    public UserLoginDTO login(UserLoginRequest userLoginRequest) {
        AdminUserEntity adminUserEntity = this.getUserByUsername(userLoginRequest.getUsername());
        if (adminUserEntity == null) {
            throw new ServiceException("账号不存在");
        }

        boolean isPasswordMatch = this.isPasswordMatch(userLoginRequest.getPassword(), adminUserEntity.getPassword());
        if (!isPasswordMatch) {
            throw new ServiceException("密码错误");
        }

//        String accessToken = generateAccessToken();
        LocalDateTime loginTime = LocalDateTime.now();
        LocalDateTime expiresTime = loginTime.plusSeconds(jwtTokenUtil.getExpireMilliseconds()/1000);
        Date curDate = Date.from(loginTime.atZone(ZoneId.systemDefault()).toInstant());
        String jwtToken = this.generateToken(adminUserEntity, curDate); //jwt token 生成

        adminUserEntity.setAccessToken(jwtToken);
        adminUserEntity.setLoginTime(loginTime);
        this.updateById(adminUserEntity);


        UserLoginDTO userLoginDTO = new UserLoginDTO();
        userLoginDTO.setUserId(adminUserEntity.getId());
        userLoginDTO.setUsername(adminUserEntity.getUsername());
        userLoginDTO.setJwtToken(jwtToken);
        userLoginDTO.setExpiresTime(expiresTime);

        return userLoginDTO;
    }

    /**
     * 生成jwttoken
     *
     * @param adminUserEntity
     * @param loginDate 登录时间
     * @return
     */
    public String generateToken(AdminUserEntity adminUserEntity, Date loginDate) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", adminUserEntity.getId());
        claims.put(JwtTokenUtil.CLAIM_KEY_USERNAME, adminUserEntity.getUsername());
        claims.put(JwtTokenUtil.CLAIM_KEY_CREATED, loginDate.getTime());
        String token = jwtTokenUtil.generateToken(claims, loginDate);
        return token;
    }

}
